package com.stackoverflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public abstract class ListItemGetter extends AsyncTask<Object, ListItem, Boolean> {
	private ProgressDialog progressDialog;
	private Context context;
	private ListView list;
	
	public ListItemGetter(Context context, ListView list)
	{
		this.context = context;
		this.list = list;
	}
	
	@Override
	protected void onPreExecute() {
		progressDialog = ProgressDialog.show(context, "", "Loading...", true, true);
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		progressDialog.dismiss();
	}

	@Override
    protected void onProgressUpdate(ListItem... values) {
		// populate some test data into our list
		ArrayList<HashMap> items = new ArrayList<HashMap>();
	    for (ListItem l : values) {
			HashMap item = new HashMap();
			if (l.getTitle().equals(""))
				item.put("text", l.getText());
			else
				item.put("text", l.getTitle());
	        item.put("owner", "posted by " + l.getOwner());
	        item.put("score", l.getScore() + " points");
	        item.put("self", l);
	        items.add(item);
        }
	    
	    if (values.length == 0)
	    {
	    	HashMap item = new HashMap();
	        item.put("text", "No items");
	        item.put("owner", "");
	        item.put("score", "");
	        item.put("self", null);
	        items.add(item);
	    }

		SimpleAdapter sa = new SimpleAdapter(
		        context.getApplicationContext(),
		        (List<? extends Map<String, ?>>) items,
		        R.layout.list_item,
		        new String[] { "text", "owner", "score" },
		        new int[] { R.id.TEXT, R.id.OWNER, R.id.SCORE }) {
		    };
        
        list.setAdapter(sa);
    }
	
}